﻿using UnityEngine;
using System.Collections;

public class Loader
{
	public enum LoaderType
	{
		STREAM,			// 流(原则上可以是任何文件,包括远程服务器上的)
		ASSET,			// Asset目录下的资源
		RESOURCE,		// Resource目录下的资源
		BUNDLE,			// AssetBundle
		SCENE,			// 场景
		BUNDLEASSET,	//AB中的资源加载
	}

	public enum LoaderState
	{
		NONE,			// 
		LOADING,		// 加载中
		FINISHED,		// 完成
	}

	public delegate void ProgressHandle(Loader loader, float rate);
	public delegate void LoadedHandle(Loader loader, object data);

	protected LoaderType m_type;			// 加载器类型
	protected LoaderState m_state;			// 加载状态
	protected string m_path;				// 路径
	protected object m_param;				// 附加参数
	protected bool m_async;					// 是否异步

	protected ProgressHandle m_onProgress;	// 加载进度
	protected LoadedHandle m_onLoaded;		// 完成回调

	protected Loader(LoaderType type)
	{
		m_type = type;
	}

	public LoaderType Type { get { return m_type; } }
	public LoaderState State { get { return m_state; } }
	public string Path { get { return m_path; } }
	public bool IsFinish { get { return State == LoaderState.FINISHED; } }
    public bool IsAsync { get { return m_async; } }

	//改成同步加载方式
	public void ChangeToSync()
	{
		m_async = false;
	}

	protected System.Diagnostics.Stopwatch m_watch;

	public virtual void Init(string path, object param, ProgressHandle onProgress, LoadedHandle onLoaded, bool async = true)
	{
		m_state = LoaderState.NONE;
		m_path = path;
		m_param = param;
		m_async = async;

		m_onProgress = onProgress;
		m_onLoaded = onLoaded;

		m_watch = new System.Diagnostics.Stopwatch ();
	}

	public virtual void Load()
	{
		m_watch.Reset ();
		m_watch.Start ();
		m_state = LoaderState.LOADING;
		OnLoadProgress(0f);
	}

	public virtual void Stop()
	{
		Reset();
	}

	public virtual void Update(float dt)
	{

	}

	protected virtual void Reset()
	{
		m_path = "";
		m_onLoaded = null;
		m_async = true;
	}

	protected virtual void OnLoadProgress(float rate)
	{
		if (m_onProgress != null)
		{
			m_onProgress(this, rate);
		}

	}

	protected void OnLoadCompleted(object data)
	{
		m_state = LoaderState.FINISHED;

		if(m_onLoaded != null)
		{
			m_onLoaded(this, data);
		}

        OnLoadProgress(1f);
		Reset();
	}
}